//
//  FeedViewController.swift
//  Story
//
//  Created by 汤泽川 on 2019/3/30.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import Foundation
import UIKit
import RxSwift
import PKHUD

class FeedViewController: UIViewController, STPageViewDelegate, STSegmentViewDelegate, STFeedListViewDelegate, UINavigationControllerDelegate {
    
    private let searchBar = STSearchBar()
    private var segmentView : STSegmentView?
    private var pagesView : STPageView?
    private var searchService = STSearchListServiceManager(pageCount: 5)
    private var searchListView : STFeedListView?
    private let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        buildView()
        initData()
    }
    
    deinit {
        self.navigationController?.delegate = nil
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        searchBar.snp.updateConstraints { (make) in
            make.top.equalToSuperview().offset(self.view.safeAreaInsets.top + 8)
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
            make.height.equalTo(34)
        }
        
        segmentView?.snp.updateConstraints({ (make) in
            make.top.equalTo(searchBar.snp_bottom).offset(4)
            make.left.right.equalToSuperview()
            make.height.equalTo(40)
        })
        pagesView?.snp.updateConstraints({ (make) in
            make.top.equalTo(segmentView!.snp_bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-self.view.safeAreaInsets.bottom)
        })
        searchListView?.snp.updateConstraints { (make) in
            make.top.equalTo(segmentView!)
            make.bottom.left.right.equalTo(pagesView!)
        }
    }
    
    private func buildView() {
        self.navigationController?.delegate = self
        self.view.addSubview(searchBar)
        
        segmentView = STSegmentView()
        segmentView?.delegate = self
        self.view.addSubview(segmentView!)
        
        pagesView = STPageView()
        pagesView?.pageDelegate = self
        self.view.addSubview(pagesView!)
        
        searchListView = STFeedListView(serviceManager: searchService)
        self.view.addSubview(searchListView!)
        searchListView?.alpha = 0;
        searchListView?.listViewDelegate = self
    }
    
    private func initData() {
        STStoryService().fetchStoryCategotyInfo().result {[weak self] (categorys, error) in
            if let categorys = categorys {
                self?.segmentView?.updateSegment(items: categorys.map({ (model) -> String in
                    return model.channelName
                }))
                self?.pagesView?.updatePages(pages: categorys.map({ (model) -> UIView in
                    let listView = STFeedListView(serviceManager: STFeedListServiceManager(channelId: model.channelId))
                    listView.triggerRefreshing()
                    listView.listViewDelegate = self
                    return listView
                }))
                self?.segmentView?.updateSelectItem(index: 0)
            }
            if let error = error {
                HUD.flash(.labeledError(title: nil, subtitle: error.localizedDescription), delay: 1.5)
            }
        }
        searchBar.searchingObserver.subscribe(onNext: {[weak self] result in
            UIView.animate(withDuration: 0.25, animations: {
                self?.searchListView?.alpha = result ? 1 : 0
            })
        }).disposed(by: disposeBag)
        self.searchListView?.feedTableView.rx.didEndDragging.asObservable().subscribe {[weak self] (event) in
            self?.searchBar.textField.resignFirstResponder()
        }.disposed(by: disposeBag)
        self.searchBar.textField.rx.text.changed.filter{ $0 != "" }.debounce(2, scheduler: MainScheduler.instance).distinctUntilChanged().subscribe(onNext: { (str) in
            self.searchService.keyword = str
            self.searchListView?.triggerRefreshing()
        }).disposed(by: disposeBag)
    }
    
    func didScrollToPage(currentPage: Int) {
        self.segmentView?.updateSelectItem(index: currentPage)
    }
    
    func didSelectIndex(currentIndex: Int) {
        self.pagesView?.scrollToPage(pageIndex: currentIndex)
    }
    
    func didClickCell(model: STStoryInfo) {
        self.searchBar.textField.resignFirstResponder()
        print(model)
        let readVC = STReadStoryViewController(model: model)
        readVC.title = "Story"
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(readVC, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
    
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        navigationController.setNavigationBarHidden(viewController == self, animated: true)
    }
}
